package com.lvfuyang.commonproject.service.impl;

import com.lvfuyang.commonproject.service.CryptoService;
import com.lvfuyang.commonproject.util.RSAUtil;
import com.lvfuyang.commonproject.util.SM4Util;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 加密服务实现类
 */
@Slf4j
@Service
public class CryptoServiceImpl implements CryptoService {

    private String rsaPublicKey;
    private String rsaPrivateKey;
    private String currentSM4Key;

    @PostConstruct
    public void init() {
        // 启动时生成RSA密钥对
        generateRSAKeyPair();
        // 生成初始SM4密钥
        generateSM4Key();
        log.info("密钥管理服务初始化完成");
    }

    /**
     * 生成RSA密钥对
     */
    private void generateRSAKeyPair() {
        Map<String, String> keyPair = RSAUtil.generateKeyPair();
        this.rsaPublicKey = keyPair.get("publicKey");
        this.rsaPrivateKey = keyPair.get("privateKey");
        log.info("RSA密钥对生成完成");
    }

    /**
     * 生成SM4密钥
     */
    private void generateSM4Key() {
        this.currentSM4Key = SM4Util.generateKey();
        log.info("SM4密钥生成完成");
    }

    /**
     * 每30分钟更新SM4密钥
     */
    @Scheduled(fixedRate = 30 * 60 * 1000) // 30分钟
    public void updateSM4Key() {
        generateSM4Key();
        log.info("SM4密钥已更新");
    }

    @Override
    public String getRSAPublicKey() {
        return rsaPublicKey;
    }

    @Override
    public String decryptPassword(String encryptedPassword) {
        return RSAUtil.decrypt(encryptedPassword, rsaPrivateKey);
    }

    @Override
    public String getCurrentSM4Key() {
        return currentSM4Key;
    }

    @Override
    public String sm4Encrypt(String plaintext) {
        return SM4Util.encrypt(plaintext, currentSM4Key);
    }

    @Override
    public String sm4Decrypt(String ciphertext) {
        return SM4Util.decrypt(ciphertext, currentSM4Key);
    }
} 
